package com.oktest.measure.ui.fragment.login

import android.content.Intent
import android.os.Bundle
import cc.shinichi.library.tool.text.MD5Util
import com.cali.common.kt.checkedInputType
import com.cali.common.kt.jsonBody
import com.cali.libcore.base.BaseFragment
import com.cali.libcore.http.RetrofitManagement
import com.oktest.measure.BuildConfig
import com.oktest.measure.MainActivity
import com.oktest.measure.MyApp
import com.oktest.measure.R
import com.oktest.measure.http.Api
import com.oktest.measure.kt.API_SUCCESS_CODE
import com.oktest.measure.kt.resultTryContext
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.coroutines.launch
import java.util.*

/**
 * @Author hhh
 * @Date 2020/11/19
 */

class LoginFragment : BaseFragment() {

    override fun getLayoutId() = R.layout.fragment_login

    override fun initData(savedInstanceState: Bundle?) {
        initView()
    }

    override fun hasBackIcon(): Boolean {
        return false
    }

    private fun initView() {
        if (BuildConfig.DEBUG) {
            etLoginName.setText("13326573612")
            etLoginPwd.setText("Gls!123456")
        }
        btnLogin.setOnClickListener {
            login()
        }
        tvForgetPwd.setOnClickListener {
            start(VerifyCodeFragment())
        }
        boxPwdVisible.setOnCheckedChangeListener { buttonView, isChecked ->
            etLoginPwd.checkedInputType(isChecked)
        }
    }

    private fun login() = launch {
        val etName = etLoginName.text.toString().trim()
        val etPwd = etLoginPwd.text.toString().trim()
        if (etName.isEmpty()) {
            toast("用户不能为空")
            return@launch
        }
        if (etPwd.isEmpty()) {
            toast("密码不能为空")
            return@launch
        }
        loadingDialog.show()
        val map = hashMapOf("mobile" to etName, "code" to MD5Util.md5Encode(etPwd).toLowerCase(
            Locale.ROOT))
        val body = map.jsonBody()
        val loginResult = resultTryContext {
            RetrofitManagement.instance.getService(Api::class.java)
                .login(body).execute().body()
        }
        loadingDialog.dismiss()
        if (loginResult.code == API_SUCCESS_CODE) {
            MyApp.memberId = loginResult.data?.memberId?:""
            startToMain()
        } else {
            error(loginResult)
            startToMain()
        }
    }

    private fun startToMain() {
        startActivity(Intent(context, MainActivity::class.java))
        pop()
        activity?.finish()
    }


}